package com.wuyangnju.lj.simulation.master.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.wuyangnju.lj.simulation.common.CommonStrings;
import com.wuyangnju.lj.simulation.common.SlaveTask;
import com.wuyangnju.lj.simulation.master.service.ComputionException;
import com.wuyangnju.lj.simulation.master.service.ComputionService;

@SuppressWarnings("serial")
public class RequestSlaveTaskServlet2 extends HttpServlet {
	private static final Log log = LogFactory
			.getLog(RequestSlaveTaskServlet2.class);
	private static final ObjectMapper mapper = new ObjectMapper();

	private ComputionService computionService;
	{
		computionService = ComputionService.get();
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/plain");

		SlaveTask slaveTask = null;
		String slaveTaskJson = null;
		try {
			slaveTask = computionService.getSlaveTask();
			slaveTaskJson = mapper.writeValueAsString(slaveTask);
			resp.getWriter().println(slaveTaskJson);
			log.info("slave task: " + slaveTaskJson);
		} catch (ComputionException e) {
			resp.getWriter().println(
					CommonStrings.COMPUTION_EXCEPTION + ": " + e.getMessage());
			log.warn(CommonStrings.COMPUTION_EXCEPTION, e);
		} catch (Exception e) {
			log.error("request slave task fail.", e);
			resp.getWriter().println(
					"request slave task fail." + e.getMessage());
		}
	}
}
